//
//  CreateContentViewController.swift
//  iModern
//
//  Created by Ralf on 5/29/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit

class CreateContentViewController: TableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, QBImagePickerControllerDelegate
{
    var contentType: String!

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let screen      = UIScreen.mainScreen().bounds
    var imageView:      UIImageView?
    var imageThumbnail: UIImage?
    let contentData = NSMutableDictionary()
    var imageViewCell:  CreateContentViewImageCell?
    var images      = NSMutableArray()

    var asset:       ALAsset?
    var assetRep:    ALAssetRepresentation?
    var imgRef:      CGImageRef?
    var img:         UIImage?
    var scale:       Float?
    var orientation: ALAssetOrientation?

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.tableView.registerNib(UINib(nibName: "CreateContentViewImageCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "IMAGE")
        self.tableView.registerNib(UINib(nibName: "CreateContentViewPhotoAlbumCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "PHOTO_ALBUM")
        self.tableView.registerNib(UINib(nibName: "CreateContentViewTakePhotoCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "TAKE_PHOTO")
        self.tableView.registerNib(UINib(nibName: "CreateContentViewTakeVideoCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "TAKE_VIDEO")

        initBackButton()
        initNextButton()
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return 3
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        var c: UITableViewCell!

        switch indexPath.row
        {
        case 0:
            let cell = tableView.dequeueReusableCellWithIdentifier("IMAGE", forIndexPath: indexPath) as! CreateContentViewImageCell
            imageViewCell = cell
            c = cell
        case 1:
            let cell = tableView.dequeueReusableCellWithIdentifier("PHOTO_ALBUM", forIndexPath: indexPath) as! CreateContentViewPhotoAlbumCell
            c = cell
        case 2:
            let cell = tableView.dequeueReusableCellWithIdentifier("TAKE_PHOTO", forIndexPath: indexPath) as! CreateContentViewTakePhotoCell
            c = cell
        default:
            break
        }

        return c
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        let screen = UIScreen.mainScreen().bounds

        switch indexPath.row
        {
        case 0:
            return screen.size.width + 100
        default:
            return 40
        }
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        switch indexPath.row
        {
        case 0:
            break
        case 1:
            choosePhotoFromLibrary()
        case 2:
            takePhoto()
        default:
            break
        }

        _ = tableView.cellForRowAtIndexPath(indexPath)
        //cell!.shake(.Vertical)

    }

    func takePhoto()
    {
        if images.count < 9
        {
            let imagePicker = UIImagePickerController()
            imagePicker.sourceType = .Camera; imagePicker.showsCameraControls = true;

            imagePicker.delegate = self;
            imagePicker.allowsEditing = true;
            self.presentViewController(imagePicker, animated: true, completion: nil)
        }
    }

    func choosePhotoFromLibrary()
    {
//        if images.count < 9
//        {
//            var imagePicker = UIImagePickerController()
//            imagePicker.sourceType = .PhotoLibrary;
//
//            imagePicker.delegate = self; imagePicker.allowsEditing = true; self.presentViewController(imagePicker, animated: true, completion: nil)
//        }

        let imagePickerController = QBImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.allowsMultipleSelection = true
        self.navigationController?.pushViewController(imagePickerController, animated: true)

    }

    func chooseVideoFromLibrary()
    {

    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject:AnyObject]!)
    {
        if imageThumbnail == nil
        {
            self.imageThumbnail = image
        }

        imageViewCell!.addImage(image)
        images.addObject(image)

        self.tableView.reloadData()
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    func imagePickerController(imagePickerController: QBImagePickerController!, didSelectAssets assets: [AnyObject]!)
    {

        for i in 0 ..< assets.count
        {

            asset = assets[i] as? ALAsset
            assetRep = asset?.defaultRepresentation()
            imgRef = assetRep?.fullResolutionImage().takeRetainedValue()
            img = UIImage(CGImage: imgRef!)
            if imageThumbnail == nil
            {
                self.imageThumbnail = img
            }
            imageViewCell!.addImage(img!)
            images.addObject(img!)

        }

        dismissImagePickerController()


        //        asset=assets[0] as? ALAsset
        //        assetRep=asset?.defaultRepresentation()
        //        imgRef=assetRep?.fullResolutionImage().takeRetainedValue()
        //        img=UIImage(CGImage: imgRef)
        //
        //        if imageThumbnail == nil
        //        {
        //            self.imageThumbnail = img
        //        }
        //
        //        imageViewCell!.addImage(img!)
        //        images.addObject(img!)
        //        self.tableView.reloadData()
        //        dismissImagePickerController()

    }

    func imagePickerControllerCancel(imagePickerController: QBImagePickerController)
    {

        dismissImagePickerController()
    }

    func dismissImagePickerController()
    {
        if (self.presentedViewController != nil)
        {
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        else
        {
            self.navigationController?.popToViewController(self, animated: true)

        }

    }

    func initNextButton()
    {
        let button = UIBarButtonItem(image: UIImage(named: "Next-Small.png")!.imageWithRenderingMode(.AlwaysOriginal), style: .Plain, target: self, action: "loadFormView:")

        self.navigationItem.rightBarButtonItem = button
    }

    @IBAction func loadFormView(sender: AnyObject)
    {
        contentData.setValue("Image", forKey: "mediaType")
        contentData.setValue(imageThumbnail, forKey: "image")
        contentData.setValue(images, forKey: "images")

        switch contentType
        {
        case "Article":
            let controller = CreateArticleFormViewController()
            controller.article = contentData
//            if self.imageThumbnail == nil && self.videoThumbnail == nil
//            {
//                self.alertWarningMessage("请选择照片")
//                return
//            }
            self.pushViewController(controller)
        case "Advertising":
            let controller = CreateAdvertisingFormViewController()
            controller.advertising = contentData
//            if self.imageThumbnail == nil && self.videoThumbnail == nil
//            {
//                self.alertWarningMessage("请选择照片")
//                return
//            }
            self.pushViewController(controller)
        case "Task":
            let controller = CreateTaskFormViewController(data: contentData)
            self.pushViewController(controller)
        case "Appointment":
            break
        default:
            break
        }
    }

    @IBAction func segmentSelected(sender: AnyObject)
    {
        self.tableView.reloadData()
    }
}
